package com.example.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class TxtUtils {

    public static void main(String[] args) {
        printScoresFromResource();
    }

    public static void printScoresFromResource() {
        // 读取 resources 下的 scores.txt
        try (InputStream inputStream = TxtUtils.class.getClassLoader().getResourceAsStream("scores.txt")) {
            if (inputStream == null) {
                System.out.println("无法找到 scores.txt 文件");
                return;
            }

            // 读取文件内容
            String json = new Scanner(inputStream, StandardCharsets.UTF_8.name()).useDelimiter("\\A").next();

            // 解析为 JSON 数组
            JSONArray jsonArray = JSONArray.parseArray(json);
            System.out.printf("%-25s%-20s%n", "Element", "Score");
            System.out.println("---------------------------------------------");

            // 遍历输出
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject obj = jsonArray.getJSONObject(i);
                String element = obj.getString("element");
                double score = obj.getDoubleValue("score");
                System.out.printf("%-25s%-20.2f%n", element, score);
            }

        } catch (Exception e) {
            System.out.println("读取文件或解析内容出错: " + e.getMessage());
        }
    }


}
